package com.youwu.weather.base.service;

import java.io.IOException;
import java.util.List;

import com.youwu.weather.base.vo.HeWeather6;
import com.youwu.weather.base.vo.WeatherResponse;
import com.youwu.weather.base.vo.WeatherType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * WeatherDataService 实现.
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {
	private static final String WEATHER_URI = "https://free-api.heweather.net/s6/weather/";
	private static final String KEY = "1fba98d5c3954585a4571eb4d1c179ae";
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Override
	public WeatherResponse getDataByCityName(WeatherType weatherType, String cityName) {
		String uri = WEATHER_URI + weatherType.type + "?location=" + cityName + "&key=" + KEY;
		return this.doGetWeahter(uri);
	}
	
	private WeatherResponse doGetWeahter(String uri) {
 		ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
		
		ObjectMapper mapper = new ObjectMapper();
		WeatherResponse resp = null;
		List<HeWeather6> heWeather6List = null;
		String strBody = null;
		
		if (respString.getStatusCodeValue() == 200) {
			strBody = respString.getBody();
		}

		try {
			resp = mapper.readValue(strBody, WeatherResponse.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resp;
	}

}
